<?php

namespace Trawind\Helpers;

use Illuminate\Support\Str;
use Illuminate\Http\JsonResponse;
use Trawind\Basics\Enums\BusinessCode;
use Illuminate\Support\Facades\Response;

/**
 * Class ResponseHelper
 *
 * @package Trawind\Helpers
 */
class ResponseHelper
{

    /**
     * @param $data
     * @return JsonResponse
     */
    public static function ok($data): JsonResponse
    {
        return self::format($data, BusinessCode::REQUEST_OK);
    }


    /**
     * @param $data
     * @return JsonResponse
     */
    public static function create($data): JsonResponse
    {
        return self::format($data, BusinessCode::CREATED_OK);
    }


    /**
     * @param $data
     * @return JsonResponse
     */
    public static function update($data): JsonResponse
    {
        return self::format($data, BusinessCode::UPDATED_OK);
    }


    /**
     * @param $data
     * @return JsonResponse
     */
    public static function delete($data = null): JsonResponse
    {
        return self::format($data, BusinessCode::DELETED_OK);
    }


    /**
     * @param               $data
     * @param  int          $code
     * @param  string|null  $message
     * @return JsonResponse
     */
    public static function format($data, int $code = BusinessCode::REQUEST_OK, ?string $message = null): JsonResponse
    {
        is_null($message) and $message = BusinessCode::getMessage($code);

        return Response::json([
            'code' => $code,
            'message' => ___($message),
            'data' => $data
        ]);
    }


    /**
     * @param  int     $code
     * @param  string  $message
     * @param  int     $status
     * @param  array   $options
     * @return JsonResponse
     */
    public static function exception(int $code, string $message, int $status = 200, array $options = []): JsonResponse
    {
        $data = array_merge([
            'code' => $code,
            'message' => $message,
        ], $options);

        return static::cors(Response::json($data, $status));
    }


    /**
     * @param $response JsonResponse
     * @return mixed
     */
    public static function cors($response)
    {
        return $response->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS,PATCH')
            ->header('Access-Control-Allow-Headers', 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization');
    }

}
